# -*- coding: UTF-8 -*-
__author__ = 'xinhui1'


# import subprocess


def get_validator_list(conf_file_path):
    """
    read the config file, get the validators
    :param conf_file_path: the path of the config file
    :return: a list in which an item correspond to one validator
    """
    conf_file = open(conf_file_path)

    validator_list = list()
    for line in conf_file:
        if line.strip().startswith('#'):  # comment line
            continue
        if line.count(',') != 2:  # invalidate line
            continue

        validator = list()
        for string in line.split(','):
            key_value = string.split('=')
            validator.append(key_value[1].strip())
        validator_list.append(validator)

    return validator_list


def do_validate(data):
    """
    do the validation
    :param data: the data to be validated
    :return:
    """
    validator_list = get_validator_list('validators.conf')
    for validator in validator_list:
        try:
            clause = 'from validators import ' + validator[0]
            exec clause
            clause = validator[0] + '.' + validator[1] + '(data)'
            (status, message) = eval(clause)
        except (ImportError, AttributeError):
            status = int(validator[2])
            message = 'validator ' + validator[0] + '.' + validator[1] + ' dose not exist'
        except:
            status = int(validator[2])
            message = 'exception in validator ' + validator[0] + '.' + validator[1]

        if status == 0:
            print 'passed the validation of ' + validator[0] + '.' + validator[1]
        else:
            print "alert error: ", message
            # subprocess.call(["../standard_script/alert/alarm.sh", alert])
            if status == 2:
                break


if __name__ == '__main__':
    # print 'this module can not run'
    data = ['just for test', 'this is a test']

    # do_validate(data)
    # print data

    import copy
    new_data = copy.deepcopy(data)
    do_validate(new_data)
    print data

